#!/usr/bin/env bash

# Copyright (c) 2025 Shenzhen Kaihong Digital Industry Development Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

srcdir=qt-everywhere-src-${pkgver}

extra_args=()
if [ "${arch}" != "${host_arch}" ]; then
    case "${CC}" in
        *clang*):
            cc_kind=clang
            ;;
        *gcc*):
            cc_kind=g++
            ;;
    esac

    xplatform="linux-${arch}-${triple_env}-${cc_kind}"
    mkdir -p ${srcdir}/qtbase/mkspecs/${xplatform}
    cat > ${srcdir}/qtbase/mkspecs/${xplatform}/qmake.conf <<EOF
include(../linux-${cc_kind}/qmake.conf)

QMAKE_CC         = ${CC}
QMAKE_CXX        = ${CXX}
QMAKE_LINK       = \$\$QMAKE_CXX
QMAKE_LINK_SHLIB = \$\$QMAKE_CXX
QMAKE_OBJCOPY    = ${OBJCOPY}
QMAKE_STRIP      = ${STRIP}
QMAKE_AR         = ${AR} cqs
QMAKE_NM         = ${NM} -P

load(qt_config)
EOF
    cat > ${srcdir}/qtbase/mkspecs/${xplatform}/qplatformdefs.h <<EOF
#include "../linux-${cc_kind}/qplatformdefs.h"
EOF

case "${triple_env}" in
    musl|ohos):
        cat >> ${srcdir}/qtbase/mkspecs/${xplatform}/qplatformdefs.h <<EOF

#undef QT_SOCKLEN_T
#define QT_SOCKLEN_T socklen_t
EOF
        ;;
esac

    extra_args+=("-xplatform" "${xplatform}")
fi

mkdir -p build || exit 1
cd build || exit 1

../${srcdir}/configure \
    -prefix /usr \
    -sysconfdir /etc \
    -opensource \
    -confirm-license \
    "${extra_args[@]}" \
    || exit 1

make -j ${MAX_JOBS} || exit 1
